import { z } from "zod";
import db from "@/server/connector/db";
import _ from "lodash";
import { CONTENT_TYPE_ZOD, CONTENT_ZOD, PERSONAL_ZOD, TITLE_ZOD } from "@/shared/restrictions/post";
import postsService from "@/server/service/post/post-service";
import AppError from "@/shared/app-error";
import { wrapRoute } from "@/server/wrapper";
import { Post } from "@prisma/client";
import { getSessionFromRequest } from "@/server/service/session-service";

const PUT_PAYLOAD_TYPES = z.object({
  contentType: CONTENT_TYPE_ZOD,
  content: CONTENT_ZOD,
  title: TITLE_ZOD,
  personal: PERSONAL_ZOD,
});

export async function PUT(req: Request, { params: { postId } }: { params: { postId: string } }): Promise<Response> {
  return await wrapRoute(async (): Promise<{ postId: string }> => {
    const session = await getSessionFromRequest(req)
    const me = await session.getMe()

    const { contentType, content, title, personal } = PUT_PAYLOAD_TYPES.parse(await req.json());

    const post = await db.post.findUnique({ where: { id: postId, deleteTime: null } });
    if (!post) {
      throw new AppError({ code: "ERR_POST_NOT_FOUND", message: "文章不存在" });
    }

    if (post.authorId !== me.id) {
      throw new AppError({ code: "ERR_POST_NOT_FOUND", message: "文章不存在" });
    }

    await db.post.update({
      data: {
        title,
        contentType,
        content,
        personal,
        updateTime: new Date(),
      },
      where: { id: postId },
    });

    return { postId: post.id };
  });
}

export async function GET(req: Request, { params: { postId } }: { params: { postId: string } }) {
  return await wrapRoute(async (respOpts): Promise<Post> => {
    const me = await meService.getOrNullFromRequest(req);
    const post = await postsService.getPostById({ postId, me });
    if (post) {
      return post;
    }
    throw new AppError({ code: "ERR_POST_NOT_FOUND", message: "文章不存在" });
  });
}
